#include "secure_transfer.h"

secure_transfer::secure_transfer() {}

secure_transfer::~secure_transfer() {}

//send data
//if the receiver will echo the message to the sender,
//set echo=true,then the function will recv and check the 
//message echoed;if not,set echo=false
//return how many chars it sends
//if error occurs,return -1
int secure_transfer::send(unsigned char *pbuf,int size,bool echo)
{
	unsigned char *buffer = NULL;
	int i,ret=0;

	//no need to send
	if(size == 0)
		return 0;

	//no need to check the message echoed
	if(echo == false)
		return sendTty(pbuf,size);
	else
	{
		ret = sendTty(pbuf,size);
		//sending failed
		if(ret == -1)
			return -1;
		//check the message echoed
		buffer = new unsigned char[size];
		ret = recvTty(buffer,size);
		//receiving error
		if(ret == -1)
			return -1;
		//check if message echoed is equal to message sent
		for(i=0;i<size;i++)
		{
			if(pbuf[i] != buffer[i])
				break;
		}
		delete buffer;
		buffer = NULL;
		//message sent is not equal to message received
		if(i != size)
			return -1;
		else
			return size;
	}
}

//receive data
//if the receiver need to echo the message to the sender
//set echo=true,then the function will send the message
//to the sender;if not,set echo=false
//return how many chars it receives
//if error occurs,return -1
int secure_transfer::recv(unsigned char *pbuf,int size,bool echo)
{
	int i,ret=0;

	//no need to recv
	if(size == 0)
		return 0;
	//no need to echo message
	if(echo == false)
		return recvTty(pbuf,size);
	else
	{
		ret = recvTty(pbuf,size);
		//receiving failed
		if(ret == -1)
			return -1;
		//echo the message
		ret = sendTty(pbuf,size);
		//echo failed
		if(ret == -1)
			return -1;
		else
			return size;
	}
}
